
var uploader;
var iconurl = '';
var uploader1;
var iconurl1 = '';
function checkPhone(phone) {
    if(phone.search(/^1[3458]{1}[0-9]{9}$/) == -1)
        return false;
    else
        return true;
}

function checkNum(num) {
    if(num.search(/^[0-9]*$/) == -1)
        return false;
    else
        return true;
}

function checkQq(qq) {
    if(qq.search(/[1-9]\d{4,}/) == -1)
        return false;
    else
        return true;
}

var weixin = {
    status: function() {
        var status = window.getUrlParam('status');
        var code = window.getUrlParam('code');
        if(status == 'true') {
            $.ajax({
                url: window.domain + window.requestUrl.checkStatusweinUrl,
                type: 'post',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                data: {
                    code: code
                },
                success: function(res) {
                    if(typeof(res.not_login) != 'undefined') {
                        window.setCookie('go_back_link', window.location.href);
                        window.location.href = './login.html';
                        return;
                    }
                    if(res.status) {
                        $('.mediaLogined-form').show();
                        var result = res.data.info;
                        $('[data-role="iconUrl"]').attr('src', result.iconUrl);
                        $('[data-role="name"]').html(result.title);


                    } else {
                        iosOverlay({
                            text: res.msg,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        } else {
            if(code == 3) {
                iosOverlay({
                    text: decodeURIComponent(window.getUrlParam('msg')),
                    duration: 3000,
                    onbeforehide: function() {
                        window.location.href = './weixin-login.html';
                    }
                });
            } else {
                iosOverlay({
                    text: decodeURIComponent(window.getUrlParam('msg')),
                    duration: 3000,
                });
            }
        }
    },
    submit: function() {
        $(document).on('click', '[data-role="submit"]', function() {

            var qq = $('[data-role="qq"]').val();
            var $qq = $('[data-role="qq"]');
            if(qq == '' || !checkQq(qq)) {
                iosOverlay({
                    text: '请填写正确的QQ',
                    duration: 1000
                });
                return;
            }

            var fans = $('[data-role="fans"]').val();
            var $fans = $('[data-role="fans"]');
            if(fans == '' || !checkNum(fans)) {
                iosOverlay({
                    text: '请填写正确的粉丝数',
                    duration: 1000
                });
                return;
            }

            var readcount = $('[data-role="readcount"]').val();
            var $readcount = $('[data-role="readcount"]');
            if(readcount == '' || !checkNum(readcount)) {
                iosOverlay({
                    text: '请填写正确的参考阅读量',
                    duration: 1000
                });
                return;
            }


            var ttbj = $('[data-role="ttbj"]').val();
            var $ttbj = $('[data-role="ttbj"]');
            var ctbj = $('[data-role="ctbj"]').val();
            var $ctbj = $('[data-role="ctbj"]');
            if(ttbj == '' && ctbj == '') {
                iosOverlay({
                    text: '头条价格和非头条价格至少填写一项',
                    duration: 1000
                });
                return;
            }

            if(iconurl == '') {
                iosOverlay({
                    text: '请上传粉丝截图',
                    duration: 1000
                });
                return;
            }

            if(iconurl1 == '') {
                iosOverlay({
                    text: '请上传阅读数截图',
                    duration: 1000
                });
                return;
            }

            if($('.plus-tag a').length == 0) {
                iosOverlay({
                    text: '请选择分类标签',
                    duration: 1000
                });
                return;
            }

            if(checkNum(fans) && checkNum(readcount) && checkQq(qq) && (ttbj != '' || ctbj != '' && iconurl != '' && iconurl1 != '') && $('.plus-tag a').length > 0) {
                var tagArr = [];
                $.each($('.plus-tag a'), function(index, item) {
                    tagArr.push($(item).attr('data-id'));
                })
                var obj = {
                    qq: qq,
                    tagJsonArr: tagArr,
                    positionJsonObj: {"province": $('#province').val(), "city": $('#city').val(), "county": $('#county').val()},
                    price1: ttbj == '' ? -1 : ttbj,
                    price2: ctbj == '' ? -1 : ctbj,
                    img1: iconurl,
                    img2: iconurl1,
                    img1num: fans,
                    img2num: readcount
                };
                $.ajax({
                    url: window.domain + window.requestUrl.addWeixinUrl,
                    type: 'post',
                    data: {
                        uParams: JSON.stringify(obj)
                    },
                    xhrFields: {
                        withCredentials: true
                    },
                    crossDomain: true,
                    success: function(res) {
                        if(typeof(res.not_login) != 'undefined') {
                            window.setCookie('go_back_link', window.location.href);
                            window.location.href = './login.html';
                            return;
                        }
                        if(res.status) {
                            window.location.href = './weixin-show.html';
                        } else {
                            iosOverlay({
                                text: res.msg,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })
            }
        })
    },
    addTag: function() {
        $.ajax({
            url: window.domain + window.requestUrl.getPlatTagUrl + '4',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                if(typeof(res.not_login) != 'undefined') {
                    window.setCookie('go_back_link', window.location.href);
                    window.location.href = './login.html';
                    return;
                }
                if(res.status) {
                    var tags = res.data.tags;
                    var tpl = '';
                    $.each(tags, function(index, item) {
                        tpl += '<a value="-1" title="'+item.tag+'" data-id="'+item.id+'" href="javascript:void(0);"><span>'+item.tag+'</span><em></em></a>';
                    })
                    $('.default-tag .clearfix').html(tpl);
                } else {
                    iosOverlay({
                        text: res.msg,
                        duration: 1000
                    });
                }
            },
            error: function(e) {
            }
        })
    },
    upload: function() {
        $(document).on('click', '.delHadImg', function() {
            $('#uploader').show();
            $(this).closest('.uploaded-wrap').remove();
            weixin.upload();
            iconurl = '';
        })
        $(document).on('click', '.uploaddel', function() {
            $(this).closest('.file-item').remove();
            uploader.removeFile( $(this).attr('data-id') , true);
        })

        uploader = WebUploader.create({
            auto: true,
            method: 'POST',
            // swf文件路径
            swf: '/assets/webuploader/Uploader.swf',

            // 文件接收服务端。
            server: './config/ueditor?action=uploadimage',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#filePicker',
            duplicate: true,
            fileNumLimit: 1,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png'
            },
            fileSingleSizeLimit: 1024*1024
        });

        uploader.on( 'fileQueued', function( file ) {
            var $li = $(
                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                        '<img>' +
                        '<div class="delPic uploaddel" data-id="'+file.id+'">删除</div>' +
                    '</div>'
                    ),
                $img = $li.find('img');

            $('#fileList').append( $li );

            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            uploader.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }

                $img.attr( 'src', src );
            }, 80, 80 );
        });

        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress span');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<p class="progress"><span></span></p>')
                        .appendTo( $li )
                        .find('span');
            }

            $percent.css( 'width', percentage * 100 + '%' );
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on( 'uploadSuccess', function( file , res) {

            $( '#'+file.id ).addClass('upload-state-done');
            iconurl = res.url;
        });

        // 文件上传失败，显示上传出错。
        uploader.on( 'uploadError', function( file ) {
            var $li = $( '#'+file.id ),
                $error = $li.find('div.error');

            // 避免重复创建
            if ( !$error.length ) {
                $error = $('<div class="error"></div>').appendTo( $li );
            }

            $error.text('上传失败');
        });

        // 完成上传完了，成功或者失败，先删除进度条。
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').remove();
        });

        uploader.on( 'error', function( type ) {
            if(type=="F_EXCEED_SIZE") {
                iosOverlay({
                    text: '文件大小不能超过1M',
                    duration: 1000
                });
            }
        });


    },
    upload1: function() {
        $(document).on('click', '.delHadImg1', function() {
            $('#uploader1').show();
            $(this).closest('.uploaded-wrap').remove();
            weixin.upload1();
            iconurl1 = '';
        })
        $(document).on('click', '.upload1del', function() {
            $(this).closest('.file-item').remove();
            uploader1.removeFile( $(this).attr('data-id') , true);
        })

        uploader1 = WebUploader.create({
            auto: true,
            method: 'POST',
            // swf文件路径
            swf: '/assets/webuploader/Uploader.swf',

            // 文件接收服务端。
            server: './config/ueditor?action=uploadimage',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#filePicker1',
            duplicate: true,
            fileNumLimit: 1,
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/jpg,image/jpeg,image/png'
            },
            fileSingleSizeLimit: 1024*1024
        });

        uploader1.on( 'fileQueued', function( file ) {
            var $li = $(
                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                        '<img>' +
                        '<div class="delPic upload1del" data-id="'+file.id+'">删除</div>' +
                    '</div>'
                    ),
                $img = $li.find('img');

            $('#fileList1').append( $li );

            // 创建缩略图
            // 如果为非图片文件，可以不用调用此方法。
            // thumbnailWidth x thumbnailHeight 为 100 x 100
            uploader1.makeThumb( file, function( error, src ) {
                if ( error ) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }

                $img.attr( 'src', src );
            }, 80, 80 );
        });

        uploader1.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress span');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<p class="progress"><span></span></p>')
                        .appendTo( $li )
                        .find('span');
            }

            $percent.css( 'width', percentage * 100 + '%' );
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader1.on( 'uploadSuccess', function( file , res) {

            $( '#'+file.id ).addClass('upload-state-done');
            iconurl1 = res.url;
        });

        // 文件上传失败，显示上传出错。
        uploader1.on( 'uploadError', function( file ) {
            var $li = $( '#'+file.id ),
                $error = $li.find('div.error');

            // 避免重复创建
            if ( !$error.length ) {
                $error = $('<div class="error"></div>').appendTo( $li );
            }

            $error.text('上传失败');
        });

        // 完成上传完了，成功或者失败，先删除进度条。
        uploader1.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').remove();
        });

        uploader1.on( 'error', function( type ) {
            if(type=="F_EXCEED_SIZE") {
                iosOverlay({
                    text: '文件大小不能超过1M',
                    duration: 1000
                });
            }
        });


    },
    moduleShow: function() {
        $('#fansshow').lightbox();
        $('#readshow').lightbox();
    },
    init: function() {
        this.status();
        this.submit();
        this.addTag();
        this.upload();
        this.upload1();
        this.moduleShow();
    }
}
weixin.init();
